package com.deram.ctin.serv.search.solr.config;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.solr.SolrProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.data.solr.server.support.EmbeddedSolrServerFactoryBean;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Configuration
@ConditionalOnClass({ HttpSolrClient.class, CloudSolrClient.class })
@EnableConfigurationProperties(SolrProperties.class)
public class SolrAutoConfiguration {

    private SolrProperties solrProperties;

    private SolrClient solrClient;

    @Resource
    private Environment environment;

    public SolrAutoConfiguration(SolrProperties properties) {
        this.solrProperties = properties;
    }


    @Bean
    public SolrClient solrClient(){
        this.solrClient = createSolrClient();
        return this.solrClient;
    }

    private SolrClient createSolrClient() {
        if (StringUtils.hasText(this.solrProperties.getZkHost())) {
            return new CloudSolrClient(this.solrProperties.getZkHost());
        }
        return new HttpSolrClient(this.solrProperties.getHost());
    }





    @Bean
    public SolrTemplate solrTemplate() throws Exception {
        return new SolrTemplate(createSolrClient());
    }


}